package nqueens.algorithm;

import nqueens.config.GAProperties;
import nqueens.core.Chromosome;

public class ObjectiveCalculator {
	
	public double calcObjective(Chromosome c) {
		int collisions = countCollisions(c);
//		System.out.println("col = " + collisions);
		int numQueens = GAProperties.getInstance().getInteger(GAProperties.NUM_QUEENS);
		int maxCollisions = calcMaxCollisions(numQueens);
//		System.out.println("max = " + maxCollisions);
		return 1.0 - (collisions/(double)maxCollisions);
	}

	private int calcMaxCollisions(int n) {
		return (n * (n-1)) / 2;
	}

	private int countCollisions(Chromosome c) {
		int counter = 0;
		int[] values = c.getValues();
		for (int i = 0; i < values.length; i++) {
			for (int j = i+1; j < values.length; j++) {
				if (is_attacking(values[i], i, values[j], j))
					counter++;
			}
		}
		return counter;
	}

	private boolean is_attacking(int i1, int j1, int i2, int j2) {
		return i1 == i2 || j1 == j2 || Math.abs(j2-j1) == Math.abs(i2-i1) || (Math.abs(j2-j1) == -Math.abs(i2-i1));
	}
	
	public static void main(String[] args) {
		GAProperties.getInstance().setInteger(GAProperties.NUM_QUEENS, 4);
		
		ObjectiveCalculator calc = new ObjectiveCalculator();
		Chromosome c = new Chromosome(new int[]{1,3,3,2});
		double d = calc.calcObjective(c);
		System.out.println(d);
	}
	
}
